package algorithms;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizen
 * 存在整型数组，只有一个唯一数字，其他都是存在两个相同的数字，请找出唯一的数字
 */
public class XORGetUniqueNumber {
    public static void test() {
        int[] nums =new int[] {1, 2, 2, 3, 3};
        System.out.println(XORGetUniqueNumberAlgorithm(nums));
        System.out.println(getAfterSort(nums));
        System.out.println(getUniqueByMap(nums));
    }

    public static int getAfterSort(int[] intList) {
        Arrays.sort(intList);
        for (int i = 0; i < intList.length - 1; i += 2) {
            if (intList[i] != intList[i + 1]) {
                return intList[i];
            }
        }
        return -1;
    }

    public static int getUniqueByMap(int[] intList) {
        Map<Integer, Integer> numCountMap = new HashMap<>();
        for (int num : intList) {
            numCountMap.put(num, numCountMap.getOrDefault(num, 0) + 1);
        }

        for (Map.Entry<Integer, Integer> entry : numCountMap.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getValue();
            }
        }

        return -1;
    }

    public static int XORGetUniqueNumberAlgorithm(int[] intList) {
        int result = 0;
        for(int num : intList) {
            result ^= num;
        }
        return result;
    }
}
